package com.jjrwa.action;


import com.intellij.codeInspection.LocalQuickFix;
import com.intellij.codeInspection.ProblemDescriptor;
import com.intellij.openapi.project.Project;
import com.intellij.psi.*;
import org.jetbrains.annotations.Nls;
import org.jetbrains.annotations.NotNull;

public class AddIdFieldQuickFix implements LocalQuickFix {

    @Override
    public @Nls
    @NotNull String getName() {
        return "Generate @Id field";
    }

    @Override
    public @Nls
    @NotNull String getFamilyName() {
        return "Generate @Id field";
    }

    @Override
    public void applyFix(@NotNull Project project, @NotNull ProblemDescriptor descriptor) {
        PsiElement element = descriptor.getPsiElement();
        if (element == null || !(element.getParent() instanceof PsiClass)) {
            return;
        }
        PsiClass psiClass = (PsiClass) element.getParent();

        PsiElementFactory factory = JavaPsiFacade.getElementFactory(project);

        String fieldText = "@ApiModelProperty(\"id\")\n@Id\nprivate String id;";
        PsiField idField = factory.createFieldFromText(fieldText, psiClass);

        PsiImportList importList = ((PsiJavaFile) psiClass.getContainingFile()).getImportList();
        if (importList != null) {
            // 自动导入 @ApiModelProperty 和 @Id 注解
            addImportIfNeeded(importList, "javax.persistence");
        }
        // 添加字段
        psiClass.add(idField);
    }

    /**
     * 自动添加导入语句（如果没有的话）
     */
    private void addImportIfNeeded(PsiImportList importList, String className) {
        PsiImportStatementBase importStatement = importList.findSingleImportStatement(className);
        if (importStatement == null) {
            PsiElementFactory factory = JavaPsiFacade.getElementFactory(importList.getProject());
            // 直接创建导入语句
            PsiImportStatementBase newImport = factory.createImportStatementOnDemand(className);
            importList.add(newImport);
        }
    }

}
